package com.server.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.server.authority.Login;
import com.server.common.base.Message;
import com.server.common.base.ProjectInfor;
import com.server.common.base.SessionData;
import com.server.service.ICommonDataService;
import com.server.service.IMsgManagementService;
import com.server.service.IMsgService;
import com.server.web.DataVector;
import com.server.web.JSONSerielizer;
import com.server.web.OutputUtil;
import com.server.web.RequestInput;
import com.server.web.SessionUtil;

/**
 * 消息管理
 * @author ServerZhang
 * @date 2016年8月18日
 */
@Controller
@RequestMapping("msg/mng")
public class MsgManagementController {
	
	private final String msgTable = "education.message";

	@Autowired
	private IMsgService msgService;
	@Autowired
	private SimpMessagingTemplate template;
	@Autowired
	private IMsgManagementService msgManagementService;
	@Autowired
	private ICommonDataService commonDataService;
	

	/**
	 * 获取消息列表
	 * @author ServerZhang
	 * @date 2016年8月22日
	 */
	@RequestMapping("")
	public ModelAndView page(HttpServletRequest request){
		ModelAndView mv = null;
		String userName = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		if (StringUtils.isEmpty(userName)) {
			return new ModelAndView("mngLogin/login");
		}else {
			mv = new ModelAndView("message/msgList");
		}
		mv.addObject("userName",userName);
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		return mv;
	}
	 /**
	 * 推送管理列表
	 * @param request
	 * @param response
	 * @param type 0为我创建的消息，1为系统消息
	 * @author ServerZhang
	 * @date 2016年8月23日
	 */
	@RequestMapping("list/{type}")
	public void list(HttpServletRequest request,
			HttpServletResponse response,@PathVariable Integer type) {
		String userName = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		DataVector<Map<String, Object>> listData = null;
		RequestInput requestInput = new RequestInput(request);
		if (type.equals(0)) {
			listData = msgManagementService.getListByCreater(userName, requestInput);
		}else {
			listData = msgManagementService.getListBySys(requestInput);
		}
		OutputUtil.returnGridData(response, listData.getCount(), JSONSerielizer.toJson(listData.getList(), null, null));
	}
	@Login
	@RequestMapping("add")
	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) {
		String userName = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		ModelAndView mv = new ModelAndView("/common/editFrame");
		mv.addObject("pagePath","pages/message/msgForm.jsp");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addObject("action", "new");
		mv.addObject("state", 0);
		mv.addObject("type", 1);
		mv.addObject("uuid", 0);
		mv.addObject("business", "msg/mng");
		mv.addObject("titleName", "新增消息推送");
		mv.addObject("userName", userName);
		return mv;
	}
	@RequestMapping("save/{uuid}")
	public void save(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String uuid){
		String operator = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		String formData = request.getParameter("formData");
		Map<String, Object> saveMap = JSONSerielizer.toMap(formData);
		List<String> users = new ArrayList<String>();
		Object usersObj = saveMap.get("uuids");
		if (usersObj != null) {
			String[] split = usersObj.toString().split(",");
			for(String str : split){
				users.add(str);
			}
		}
		Object pushTypeObj = saveMap.get("pushType");
		Boolean pushNow = true;//即时推送
		if (pushTypeObj != null && "1".equals(pushTypeObj.toString())) {
			pushNow = false;
		}
		saveMap.remove("users");
		saveMap.remove("uuids");
		Boolean isSuccess = true;
		if (uuid.equals("0")) {
			uuid = UUID.randomUUID().toString();
			saveMap.put("uuid", uuid);
			Integer add = msgManagementService.add(operator, users, saveMap);
			isSuccess = add > 0;
			if (isSuccess) {
				//放入内存等待推送
				Map<String, Object> map = new HashMap<String, Object>();
				if (pushNow) {
					map.put("pushTime", new Date());
				}else{
					map.put("pushTime", saveMap.get("pushTime"));
				}
				map.put("uuid", uuid);
				map.put("msgName", saveMap.get("msgName"));
				msgManagementService.addPrePushData(map);
			}
		}else {
			isSuccess = commonDataService.update(operator, msgTable, "uuid", uuid, saveMap);
			if (isSuccess) {
				//重新放入内存等待推送
				Map<String, Object> map = new HashMap<String, Object>();
				if (pushNow) {
					map.put("pushTime", new Date());
				}else{
					map.put("pushTime", saveMap.get("pushTime"));
				}
				map.put("uuid", uuid);
				map.put("msgName", saveMap.get("msgName"));
				msgManagementService.updatePrePushData(uuid,map);
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("isSuccess", isSuccess);
		map.put("uuid", uuid);
		OutputUtil.returnString(response, JSONSerielizer.toJson(map, null, null));
	}
	@Login
	@RequestMapping("update/{uuid}/{state}")
	public ModelAndView update(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String uuid,
			@PathVariable Integer state) {
		String userName = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		ModelAndView mv = new ModelAndView("/common/editFrame");
		mv.addObject("pagePath","pages/message/msgForm.jsp");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addObject("action", "edit");
		mv.addObject("state", state);
		mv.addObject("type", 1);
		mv.addObject("uuid", uuid);
		mv.addObject("business", "msg/mng");
		mv.addObject("titleName", "编辑消息推送");
		mv.addObject("userName", userName);
		return mv;
	}
	@Login
	@RequestMapping("check/{uuid}/{state}")
	public ModelAndView check(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String uuid,
			@PathVariable Integer state) {
		String userName = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		ModelAndView mv = new ModelAndView("/common/editFrame");
		mv.addObject("pagePath","pages/message/msgForm.jsp");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addObject("action", "check");
		mv.addObject("state", state);
		mv.addObject("type", 1);
		mv.addObject("uuid", uuid);
		mv.addObject("business", "msg/mng");
		mv.addObject("titleName", "查看消息推送");
		mv.addObject("userName", userName);
		return mv;
	}
	@RequestMapping("form/{uuid}")
	public void form(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String uuid){
		Map<String, Object> formData = msgManagementService.getForm(uuid);
		OutputUtil.returnString(response, JSONSerielizer.toJson(formData, null, null));
	}
	
	/*
	 * 测试用的
	 */
	@RequestMapping("push")
	public ModelAndView push(HttpServletRequest request) {
		List<String> users = new ArrayList<String>();
		users.add("test-uuid");
		this.sendMsgToUser("消息推送", users);
		return new ModelAndView("common/empty");
	}
	/*
	 * 测试用的
	 */
	@RequestMapping("send")
	public void send(HttpServletRequest request) {
		msgManagementService.autoPush();
	}

	/**
	 * 指定用户推送消息
	 * 
	 * @param msg
	 * @param users
	 * @author ServerZhang
	 * @date 2016年8月18日
	 */
	private void sendMsgToUser(String msg, List<String> users) {
		
		Iterator<String> iterator = users.iterator();
		while (iterator.hasNext()) {
			List<Message> msgList = new ArrayList<Message>();
			String next = iterator.next();
			if (StringUtils.isEmpty(next)) {
				continue;
			}
			Message message = new Message();
			message.setLoginName(next);
			message.setMsgContent(msg);
			msgList.add(message);
			template.convertAndSend("/topic/msgfetch/" + next, msgList);
		}
	}
	 /**
	 * 自动推送
	 * @author ServerZhang
	 * @date 2016年8月24日
	 */
	@RequestMapping("autoPush")
	public ModelAndView autoPush(){
		List<Map<String, Object>> preData = msgManagementService.getPrePushData();
		Iterator<Map<String, Object>> iterator = preData.iterator();
		Calendar instance = Calendar.getInstance();
//System.out.println("自动推送时间："+instance.getTime());
		long time = instance.getTime().getTime();
		while(iterator.hasNext()){
			Map<String, Object> next = iterator.next();
			Object pushTimeObj = next.get("pushTime");
			if (pushTimeObj == null){
				pushTimeObj = instance.getTime();
			}
			Object uuidObj = next.get("uuid");
			Object msgNameObj = next.get("msgName");
			String msgName = msgNameObj != null ? msgNameObj.toString() : "";
			if (pushTimeObj != null && uuidObj != null) {
				Date date = (Date)pushTimeObj;
				long setTime = date.getTime();
				if (setTime <= time || setTime - time <= 30000) {
					//1.获取该消息的所有接收人
					List<String> users = msgManagementService.getUsers(uuidObj.toString());
					//2.向以上接收人推送消息
					this.sendMsgToUser(msgName, users);
					//3.修改该消息状态并清除内存中的记录
					msgManagementService.updateState(uuidObj.toString());
				}
			}
		}
		return new ModelAndView("common/empty");
	}
	/**
	 * 获取消息列表
	 * @author ServerZhang
	 * @date 2016年8月22日
	 */
	@RequestMapping("addUsers")
	public ModelAndView addUsers(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("message/addUsers");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		return mv;
	}

	/**
	 * 删除
	 * @param request
	 * @param response
	 * @author ServerZhang
	 * @date 2016年8月31日
	 */
	@RequestMapping("delete")
	public void delete(HttpServletRequest request, HttpServletResponse response) {
		String userName = SessionUtil.getStringAttri(request,
				SessionData.nameKey_mng);
		String uuids = request.getParameter("uuids");
		Integer deleteInfo = msgManagementService.delete(uuids, userName);
		OutputUtil.returnString(response, deleteInfo.toString());
	}
}
